<template>
  <el-form :model="empForm" :inline="true" style="margin-bottom: 10px;" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="empForm.name" style="width: 120px;" placeholder="请输入员工姓名"></el-input>
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="empForm.gender" style="width: 100px;" placeholder="请选择">
        <el-option label="男" value="1"></el-option>
        <el-option label="女" value="2"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="账号">
      <el-input v-model="empForm.account" style="width: 120px;" placeholder="请输入员工账号"></el-input>
    </el-form-item>
    <el-form-item label="创建时间">
      <el-date-picker v-model="empForm.data" type="daterange" value-format="YYYY-MM-DD" 
      range-separator="至" start-placeholder="开始日期"
        end-placeholder="结束日期" style="width: 350px; margin-left: 10px" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="findEmpMessageByCondition">查询</el-button>
      <el-button type="info" @click="clearEmpForm">清空</el-button>
    </el-form-item>
  </el-form>
  <div style="justify-content: space-between;">
    <el-button type="primary" @click="dialogVisible = true">新增员工</el-button>
    <el-button type="danger" @click="deleteByIds">批量删除</el-button>
    <el-button type="success" @click="settlementSalaryByIds">批量结算工资</el-button>
  </div>
  <el-table :data="tableData" border style="width: 100%;margin-bottom: 10px;margin-top: 10px;"
    @selection-change="getSelectedMessage">
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" label="id" style="width: 50px;" />
    <el-table-column property="name" label="员工姓名" width="85" />
    <el-table-column property="gender" label="员工性别" width="85">
      <template #default="scope">
        <span>
          {{ scope.row.gender === 1 ? '男' : '女' }}
        </span>
      </template>
    </el-table-column>
    <el-table-column prop="image" label="员工头像" align="center" width="85">
      <template #default="scope">
        <img style="width: auto; height: 40px; border: none; cursor: pointer" :src="scope.row.image">
      </template>
    </el-table-column>
    <el-table-column align="center" property="account" label="员工账号"  width="90"/>
    <el-table-column align="center" property="password" label="员工密码"  width="90"/>
    <el-table-column align="center" property="createTime" label="创建时间" width="100" />
    <el-table-column align="center" property="salary" label="员工工资" width="90" />
    <el-table-column align="center" property="deductSalary" label="已扣工资" width="90" />
    <el-table-column align="center" property="trainingScore" label="培训得分" width="90" />
    <el-table-column align="center" property="lastOperationTime" label="最后操作时间" width="120" />
    <el-table-column align="center" property="status" label="登录状态" width="90" />
    <el-table-column align="center" style="width: 100px;" label="操作">
      <template #default="scope" style="justify-content: space-between;">
        <el-link style="margin-right: 10px;" target="_blank" @click="getMessageById(scope.row.id)">编辑</el-link>
        <el-link type="danger" @click="deleteById(scope.row.id)">删除</el-link>
        <el-link type="success" @click="settlementSalary(scope.row.id,scope.row.account,scope.row.deductSalary,scope.row.salary)">结算工资</el-link>
      </template>
    </el-table-column>
  </el-table>
  <div class="demo-pagination-block">
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
      :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
  <!-- 新增员工表单的对话框 -->
  <el-dialog v-model="dialogVisible" title="新增员工" width="500" draggable>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" :size="formSize" status-icon>
      <el-form-item label="员工姓名" prop="name" style="width: 250px;" placeholder="请输入员工姓名">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="员工性别" prop="gender">
        <el-select v-model="ruleForm.gender" style="width: 150px;" placeholder="请选择" clearable>
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="员工头像" prop="image">
        <el-upload class="avatar-uploader" action="/api/admin/upload" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="getTokenToHeader">
          <img v-if="ruleForm.image" :src="ruleForm.image" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="员工账号" prop="account" placeholder="请输入员工账号">
        <el-input style="width: 150px;" v-model="ruleForm.account" clearable />
      </el-form-item>
      <el-form-item label="员工密码" prop="password" placeholder="请输入员工密码">
        <el-input style="width: 150px;" v-model="ruleForm.password" />
      </el-form-item>
      <el-form-item label="员工工资" prop="salary" placeholder="请输入员工的初始工资">
        <el-input style="width: 150px;" v-model="ruleForm.salary" clearable />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="ruleForm.createTime" type="date" placeholder="请选择当前时间" :size="size" clearable />
      </el-form-item>
      <el-form-item label="最后操作时间" prop="lastOperationTime">
        <el-date-picker v-model="ruleForm.lastOperationTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择当前时间" :size="size" clearable />
      </el-form-item>
      <el-form-item style="justify-content: space-between;justify-content: center;align-items: center;display: flex;">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="resetForm(ruleFormRef)">清空</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <!-- 点击编辑跳转的对话的对话框 -->
  <el-dialog v-model="modifyDialogVisible" title="编辑员工信息" width="500" draggable>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="modifyForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" :size="formSize" status-icon>
      <el-form-item label="员工姓名" prop="name" style="width: 250px;" placeholder="请输入员工姓名">
        <el-input v-model="modifyForm.name" />
      </el-form-item>
      <el-form-item label="员工性别" prop="gender">
        <el-select v-model="modifyForm.gender" style="width: 150px;" placeholder="请选择" clearable>
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="员工头像" prop="image">
        <el-upload class="avatar-uploader" action="/api/admin/emp" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers=token>
          <img v-if="modifyForm.image" :src="modifyForm.image" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="员工账号" prop="account" placeholder="请输入员工账号">
        <el-input style="width: 150px;" v-model="modifyForm.account" clearable />
      </el-form-item>
      <el-form-item label="员工密码" prop="password" placeholder="请输入员工密码">
        <el-input style="width: 150px;" v-model="modifyForm.password" />
      </el-form-item>
      <el-form-item label="员工工资" prop="salary" placeholder="请输入员工的初始工资">
        <el-input style="width: 150px;" v-model="modifyForm.salary" clearable />
      </el-form-item>
      <el-form-item label="最后操作时间" prop="lastOperationTime">
        <el-date-picker v-model="modifyForm.lastOperationTime" type="datatime" placeholder="请选择当前时间" :size="size"
          clearable />
      </el-form-item>
      <el-form-item style="justify-content: space-between;justify-content: center;align-items: center;display: flex;">
        <el-button type="primary" @click="modifySubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElTable, ElMessage, UploadProps, dayjs } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { getToken } from '@/utils/auth';
import axios from '@/utils/request';
import moment from 'moment';
const total = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const size = ref<ComponentSize>('default')
const background = ref(true)
const disabled = ref(false)
const dialogVisible = ref(false)
const modifyDialogVisible = ref(false)
const tableData = ref([])
const currentTime = ref(moment().format('YYYY-MM-DD'));
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//复选框选中数据的集合
const tableMessageList = ref([])
//选中id的集合
const selectIdsList = ref([])
const clearEmpForm = () => {
  empForm.value.account = '';
  empForm.value.gender = '';
  empForm.value.data = ['',''];
  empForm.value.name = '';
  //刷新表格
  findAllEmpMessage();
}
//获取请求头
const token = ref({ localStorage: getToken() })

let empForm = ref({
  name:'',
  gender:'',
  account:'',
  data: ['',''],
})
//页数大小发生改变
const handleSizeChange = (val: number) => {
  //页数的值发生改变
  pageSize.value = val;
  //刷新表格
  findAllEmpMessage();
}
//当前页发生改变
const handleCurrentChange = (val: number) => {
  //当前页的值发生改变
  currentPage.value = val;
  //刷新表格
  findAllEmpMessage();
}
const ruleForm = reactive({
  name: '',
  gender: '',
  image: '',
  account: '',
  password: '123456',
  salary: '',
  createTime: currentTime,
  lastOperationTime: currentTime
})
//修改表格的对象
let modifyForm = ref({
  id: 0,
  name: '',
  gender: '',
  image: '',
  account: '',
  password: '',
  salary: '',
  lastOperationTime: currentTime
})
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 5, message: '长度必须在2到5之间', trigger: 'blur' },
  ],
  gender: [
    {
      required: true,
      message: '请选择员工性别',
      trigger: 'change',
    },
  ],
  image: [
    {
      required: true,
      message: '请上传员工头像',
      trigger: 'change',
    },
  ],
  account: [
    {
      required: true,
      message: '请输入员工账号',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入员工密码', trigger: 'blur' },
    { min: 6, message: '密码长度必须大于六', trigger: 'blur' }
  ],
  salary: [
    {
      required: true,
      message: '请输入员工工资',
      trigger: 'blur'
    }
  ],
  createTime: [
    {
      required: true,
      message: '请输入创建时间',
      trigger: 'blur'
    }
  ],
  lastOperationTime: [
    {
      required: true,
      message: '请输入最后操作时间',
      trigger: 'blur'
    }
  ]
})
//获取token
const getTokenToHeader=reactive({
  token: getToken()
})
//选中复选框后跳转的方法
const getSelectedMessage = (rows: any[]) => {
  tableMessageList.value = rows;
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  ruleForm.image = response.data;
};
const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {
  const allowedImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'];  // 定义允许的图片类型数组，可根据实际需求添加更多类型
  const isImage = allowedImageTypes.includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) {
    ElMessage.error("上传的文件必须是图片格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传的图片大小不能超过 2MB!");
  }
  return isImage && isLt2M;
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const submit = async () => {
  try {
    const result = await axios.post("/admin/emps", ruleForm);
    if (result.data.code === 1) {
      ElMessage.success("添加成功");
      dialogVisible.value = false;
      // 添加成功后刷新界面，继续发送查询所有信息的请求
      await findAllEmpMessage();
    } else {
      ElMessage.error("添加失败，该账号已经存在");
    }
  } catch (error) {
    ElMessage.error("添加员工请求出错，请检查网络或联系后台管理员");
    console.error("添加员工出错:", error);
  }
};

// 钩子方法，在组件挂载时发送异步请求获取数据
onMounted(() => findAllEmpMessage());

// 从后端获取信息的方法
const findAllEmpMessage = async () => {
  try {
    const request = await axios.get(`/admin/emps`);
    if (request.data.code === 1) {
      tableData.value = request.data.data.rows;
      total.value = request.data.data.total;
    } else {
      ElMessage.error("员工表信息获取失败，请联系后台管理员");
    }
  } catch (error) {
    ElMessage.error("获取员工信息请求出错，请检查网络或联系后台管理员");
    console.error("获取员工信息出错:", error);
  }
};

// 根据id删除员工的信息
const deleteById = async (id: any) => {
  try {
    const confirm = window.confirm('确定删除该用户信息吗？');
    if (confirm) {
      const result = await axios.delete(`/admin/emp/${id}`);
      if (result.data.code === 1) {
        ElMessage.success("删除成功");
        // 删除成功，查询所有员工信息
        await findAllEmpMessage();
      } else {
        ElMessage.error("删除失败，请联系后台管理员！");
      }
    }
  } catch (error) {
    ElMessage.error("删除员工请求出错，请检查网络或联系后台管理员");
    console.error("删除员工出错:", error);
  }
};
//批量删除员工信息的方法
async function deleteByIds() {
  // 弹出确认框，询问用户是否确定删除选中的数据
  const isConfirmed = window.confirm('确定删除选中的数据吗？');
  if (isConfirmed) {
    // 遍历选中的行数据，将每个行数据的id添加到selectIdsList数组中
    selectIdsList.value = tableMessageList.value.map(row => row.id);
    if (selectIdsList.value.length === 0) {
      // 如果没有选中任何数据，显示错误提示信息
      ElMessage.error('请选择要删除的数据！');
      return;
    }
    try {
      // 发送异步删除请求，将选中的id列表传递给后端接口
      const result = await axios.delete('/admin/emps/' + selectIdsList.value.join(','));
      if (result.data.code === 1) {
        // 如果删除成功，显示成功提示信息
        ElMessage.success('删除成功');
        // 调用函数刷新表格数据
        findAllEmpMessage();
      } else {
        // 如果删除失败，显示相应的错误提示信息，并提示联系后台管理员
        ElMessage.error('删除失败，请联系后台管理员！');
      }
    } catch (error) {
      // 如果请求过程中出现错误，比如网络问题等，显示相应的错误提示
      ElMessage.error('请求出错，请检查网络或联系后台管理员！');
      console.error('删除请求出错:', error);
    }
  }
}
//模糊查询员工表的信息
const findEmpMessageByCondition = async () => {
   //查询信息的填写不能为空
   if (empForm.value.name === '' && empForm.value.gender === '' && empForm.value.account === '' && empForm.value.data[0] === '' && empForm.value.data[1] === '') {
      ElMessage.error("查询条件不能为空！");
      return;
    }
  try {
    const result = await axios.get(`/admin/emps?page=${currentPage.value}&pageSize=${pageSize.value}&name=${empForm.value.name}&gender=${empForm.value.gender}&account=${empForm.value.account}&beginTime=${empForm.value.data[0]}&endTime=${empForm.value.data[1]}`)
    if (result.data.code === 1) {
      tableData.value = result.data.data.rows;
      total.value = result.data.data.total;
      ElMessage.success("查询成功");
    } else {
      ElMessage.error("查询失败，请检查格式是否正确");
    }
  } catch (error) {
    ElMessage.error("获取员工信息请求出错，请检查网络或联系后台管理员");
    console.error("获取员工信息出错:", error);
  }
}

//根据id获取员工信息
const getMessageById = async (id) => {
  try {
    // 发送GET请求到后端接口，根据传入的员工id获取对应的员工详细信息
    // 注意：这里拼接URL的方式可能存在问题，更安全的做法是使用模板字符串拼接，如下所示
    const result = await axios.get('/admin/emps/' + id);
    // 根据后端返回的数据中的code值来判断获取信息操作是否成功
    if (result.data.code === 1) {
      // 如果code为1，表示获取信息成功，将后端返回的员工信息数据赋值给modifyForm
      // 这样修改表单就能回显对应的员工信息，方便用户进行修改操作
      modifyForm.value = result.data.data;
      //对后端返回gender的数据进行处理
      if (modifyForm.value.gender == '1') {
        modifyForm.value.gender = '男'
      } else {
        modifyForm.value.gender = '女'
      }
      //修该最后操作时间为当前时间
      modifyForm.value.lastOperationTime = currentTime.value;
      // 将修改员工信息的对话框设置为显示状态，以便用户能看到回显的信息并进行修改
      modifyDialogVisible.value = true;

    } else {
      // 如果code不为1，表示获取信息失败，显示相应的错误提示信息，告知用户联系后台管理员
      ElMessage.error("获取信息失败，请联系后台管理员！");
    }
  } catch (error) {
    // 如果在发送请求、接收响应或者解析数据等过程中出现任何错误，都会被此catch块捕获
    // 例如网络连接问题、后端接口异常等情况
    ElMessage.error("获取员工信息请求出错，请检查网络或联系后台管理员");
    console.error("获取员工信息出错:", error);
  }
};
//提交修改完成的员工信息给前端的方法（put）
const modifySubmit = async () => {
  try {
    // 构造要传递给后端的数据对象，确保参数结构清晰准确
    //将性别数据转换为数字类型
    if (modifyForm.value.gender === '男') {
      modifyForm.value.gender = '1'
    } else {
      modifyForm.value.gender = '2'
    }
    // 发送PUT请求到后端接口，传递整理好的数据
    const result = await axios.put('/admin/emps', {
      id: modifyForm.value.id,
      name: modifyForm.value.name,
      gender: modifyForm.value.gender,
      image: modifyForm.value.image,
      account: modifyForm.value.account,
      password: modifyForm.value.password,
      salary: modifyForm.value.salary,
      lastOperationTime: modifyForm.value.lastOperationTime
    });
    if (result.data.code === 1) {
      ElMessage.success("修改成功");
      // 关闭修改员工信息的对话框
      modifyDialogVisible.value = false;
      // 刷新表格数据
      await findAllEmpMessage();
    } else {
      ElMessage.error("修改失败，请检查格式是否正确！");
    }
  } catch (error) {
    ElMessage.error("修改员工信息请求出错，请检查网络或联系后台管理员");
    console.error("修改员工信息出错:", error);
  }
};
//根据员工id结算员工工资的方法
const settlementSalary = async (id: any,account :any,deductSalary :any,salary:any) => {
  try {
    // 发送PUT请求到后端接口，传递整理好的数据
    const result = await axios.put('/admin/emp/salary',{
      id: id,
      account: account,
      salaryDate: currentTime.value,
      deductSalary: deductSalary,
      salary: salary
    });
    if (result.data.code === 1) {
      ElMessage.success("结算成功");
      // 刷新表格数据
      await findAllEmpMessage();
    } else {
      ElMessage.error("结算失败，请联系后台管理员！");
    }
  } catch (error) {
    ElMessage.error("结算员工工资请求出错，请检查网络或联系后台管理员");
    console.error("结算员工工资出错:", error);
  }
};

//批量结算员工工资的方法
const settlementSalaryByIds = async () => {
  if (tableMessageList.value.length === 0) {
    ElMessage.error("请选择要结算的员工！");
    return;
  }
  // 遍历选中的行数据，将每个行数据的id添加到selectIdsList数组中
  selectIdsList.value = tableMessageList.value.map(row => row.id);
  try {
    // 发送PUT请求到后端接口，传递整理好的数据
    const result = await axios.get('/admin/emps/salary/' + selectIdsList.value.join(','), {
      params: {
        salaryDate: currentTime.value
      }
    });
    if (result.data.code === 1) {
      ElMessage.success("结算成功");
      // 刷新表格数据
      await findAllEmpMessage();
    } else {
      ElMessage.error("结算失败，请联系后台管理员！");
    }
  } catch (error) {
    ElMessage.error("结算员工工资请求出错，请检查网络或联系后台管理员");
    console.error("结算员工工资出错:", error);
  }
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>